const http = require("http");
const fs = require("fs");
const url = require("url");
const qs = require("querystring");

http
  .createServer((req, res) => {
    if (req.url !== "/favicon.ico") {
      if (url.parse(req.url).pathname === "/api") {
        ajaxHandle(req, res);
      } else {
        fileHandle(req, res);
      }
    }
  })
  .listen("3001");

function ajaxHandle(req, res) {
  const urlObj = url.parse(req.url, true);

  let str = "";
  req.on("data", (d) => {
    str += d;
  });
  req.on("end", () => {
    let reqObj = null;
    if (str === "") {
      reqObj = urlObj.query;
    } else {
      reqObj = qs.parse(str);
    }
    if (reqObj.type === "login") {
      login(reqObj, res);
    } else {
      register(reqObj, res);
    }
  });
}

let userMsg = [];

function register(data, res) {
  let onoff = userMsg.some((val) => {
    return val.user === data.un;
  });

  if (onoff) {
    res.write(JSON.stringify({ code: 0, title: "用户名重复" }));
  } else {
    userMsg.push({
      userid: "userid_" + Math.random().toString().slice(2),
      user: data.un,
      pass: data.pw,
      flag: 0,
    });

    res.write(JSON.stringify({ code: 1, title: "注册成功" }));
  }
  console.log(userMsg);
  res.end();
}

function login(data, res) {
  console.log(data);
  let i = 0;
  let onoff = userMsg.some((val, idx) => {
    i = idx;
    return val.user === data.un;
  });
  if (onoff) {
    if (userMsg[i].pass === data.pw) {
      res.write(
        JSON.stringify({ code: 1, title: "登录成功", data: userMsg[i] })
      );

      userMsg[i].flag = 1;
    } else {
      res.write(JSON.stringify({ code: 2, title: "密码错误" }));
    }
  } else {
    res.write(JSON.stringify({ code: 0, title: "用户名不存在" }));
  }
  res.end();
}

function fileHandle(req, res) {
  fs.readFile("./www" + url.parse(req.url).pathname, (err, data) => {
    if (err) {
      res.write("404");
    } else {
      res.write(data);
    }
    res.end();
  });
}
